package project3;

import java.util.HashMap;

/** A word stemmer that caches the results of another stemmer.
 * This is provided as a memory/performance optimization.
 *
 * This improves memory usage by decreasing the number of strings in memory,
 * specifically by removing duplication. When a document stores a map from
 * stem to index entry, for 10,000 words say, if another document has many of the
 * same stems, you may only need 10,000 strings in memory; instead of the 20,000
 * that would be needed otherwise.
 *
 * Performance improvement is acheived through simple caching of input and its
 * related output; meaning the stemming algorithm isn't rerun if the word has
 * been encountered before.
 *
 * This class is only designed to work when inputs are lower case.
 */
public class CachingStemmer implements WordStemmer
{
    /** The core word stemmer to use when there is no cache hit */
    private WordStemmer stemmer;
    /** maps an input word to its stem */
    private HashMap<String, String> wordToStemMap;

    /**Builds a caching stemmer.
     * @param stemmer The stemmer that is performing the actual stemming algorithm.
     */
    public CachingStemmer(WordStemmer stemmer)
    {
        this.stemmer=stemmer;
        wordToStemMap=new HashMap<String, String>();
    }

    /** Builds a default caching stemmer, using project3.Stemmer as the wrapped stemmer. */
    public CachingStemmer()
    {
        this(new Stemmer());
    }

    /** Returns the stem of the input word */
    public String stem(String word)
    {
        //if the word is a cache hit, return it
        if(wordToStemMap.containsKey(word))
            return wordToStemMap.get(word);

        //get the stem;
        String stem = stemmer.stem(word);

        //cache the word->stem entry
        wordToStemMap.put(word, stem);
        return stem;
    }
}
